import os
import json

class PicsManager:
    # PicsManager把图片存放在data_dir中
    # 导入图片时，对图片名称进行标准化：时间+hash
    # pic_name为图片在data_dir内的路径
    # 根据图片的数量，对图片文件进行分层管理

    def __init__(self):
        self.label_file_name = 'DO_NOT_DELETE.json'
        self.label_pics = {}    # {str: set}
        self.pic_labels = {}    # {str: set}
        self.data_dir = ''
        self.default_label_file_content = '{"pic_labels":{}, "label_pics":{}}\n'

    def load(self, data_dir_name):
        if os.path.exists(data_dir_name) == False:
            raise FileNotFoundError(data_dir_name)
        self.data_dir = data_dir_name
        self.label_file_name = os.path.join(data_dir_name, self.label_file_name)
        if os.path.exists(self.label_file_name) == False:
            # label文件不存在时，新建一个空的
            with open(self.label_file_name, 'w') as f:
                f.write(self.default_label_file_content)
        else:
            with open(self.label_file_name) as f:
                content = f.read()
                js = json.loads(content)
                # 把map中的value转换成set类型
                label_pics = js['label_pics']
                for lb in label_pics:
                    self.label_pics[lb] = set(label_pics[lb])
                pic_labels = js['pic_labels']
                for pic in pic_labels:
                    self.pic_labels[pic] = set(pic_labels[pic])

    def save(self):
        js = {'pic_labels':{}, 'label_pics':{}}
        # 把map中的value转换成list类型
        pic_labels = js['pic_labels']
        for pic in self.pic_labels:
            pic_labels[pic] = list(self.pic_labels[pic])
        label_pics = js['label_pics']
        for lb in self.label_pics:
            label_pics[lb] = list(self.label_pics[lb])
        s = json.dumps(js)
        with open(self.label_file_name, 'w') as f:
            f.write(s)

    def setPicLabels(self, pic_name:str, labels:list):
        # 获取pic原有labels
        old_labels = []
        if pic_name in self.pic_labels:
            old_labels = self.pic_labels[pic_name]

        # 去掉旧的label
        if len(old_labels) > 0:
            self.pic_labels.pop(pic_name)
            for lb in old_labels:
                self.label_pics[lb].remove(pic_name)

        # 加入新的labels
        self.pic_labels[pic_name] = labels
        for lb in labels:
            if lb in self.label_pics:
                self.label_pics[lb].add(pic_name)
            else:
                self.label_pics[lb] = set([pic_name])

    def getPicsLabelInfo(self) -> list:
        return list(self.label_pics.keys())

    def getPicsByLabels(self, labels:list) -> set:
        # 检查每个label的有效性
        ok_labels = []
        for lb in labels:
            if lb in self.label_pics:
                ok_labels.append(lb)
        if len(ok_labels) == 0:
            return set()      
        ret = self.label_pics[ok_labels[0]]
        for lb in labels[1:]:
            ret = ret.intersection(self.label_pics[lb])
            if len(ret) == 0:
                return ret
        return ret

    def deletePics(self, pic_names:list):
        ...

    def getAllPicsLabels(self) -> list:
        '''返回值：[(pic_nam,[label, ...]), ...]'''
        ret = []
        for pic_name in self.pic_labels:
            ret.append((pic_name, self.pic_labels[pic_name]))
        return ret

    def check(self):
        '''检查label_pics, pic_label,和图片名是否匹配'''
        ...